package com.trg.generaltool.util.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName: RabbitmqUtil
 * @Description:
 * @Author: tangrg
 * @Date: 2021/7/16 16:55
 * @Version: 1.0
 * @Return:
 **/
public class RabbitmqUtil {
    private static ConnectionFactory connectionFactory = null;

    static {
        connectionFactory = new ConnectionFactory();
        //rabbitmq所在的主机
        connectionFactory.setHost("192.168.56.10");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("ems");
        connectionFactory.setPassword("ems");
        //设置要连接的虚拟主机
        connectionFactory.setVirtualHost("/ems");
    }

    /**
     * 获取连接
     *
     * @return
     */
    public static Connection getConnect() {
        try {
            Connection connection = connectionFactory.newConnection();
            return connection;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void closeConnect(Connection connection, Channel channel) {
        try {
            if (channel != null) channel.close();
            if (connection != null) connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
